using UnityEngine;
using UnityEngine.UI;

namespace IQIGame.Onigao.Framework
{
    public static class UICoreHelper
    {
        //支持ScrollView裁剪的URP Shader参数
        public static readonly string UIClipRect = "_UIClipRect";
        public static readonly string UIClipSoftnessRect = "_UIClipSoftnessRect";

        public static void ResetRectTransform(this RectTransform t)
        {
            t.localScale = Vector3.one;
            t.offsetMin = Vector2.zero;
            t.offsetMax = Vector2.zero;
            t.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
        }

        public static void ResetRectTransform(this GameObject uguiGo)
        {
            RectTransform rTrsf = uguiGo?.transform as RectTransform;
            rTrsf?.ResetRectTransform();
        }

        public static T GetOrAdd<T>(this GameObject go, bool isAdd = true) where T : Component
        {
            var comp = go.GetComponent<T>();
            if (isAdd && comp == null)
                comp = go.AddComponent<T>();
            return comp;
        }

        public static T GetFirstParent<T>(this GameObject go, bool includeInactive = false) where T : Component
        {
            var comps = go.GetComponentsInParent<T>(includeInactive);
            if (comps == null || comps.Length == 0)
                return null;
            T first = null;
            for (int i = 0; i < comps.Length; i++)
            {
                if (comps[i].gameObject == go)
                    continue;
                if (first != null)
                    break;
                first = comps[i];
            }
            return first;
        }

        public static void ReleaseTemporary(this RenderTexture rt)
        {
            if (rt == null)
                return;
            RenderTexture.ReleaseTemporary(rt);
        }

        public static void DestroyRenderTexture(this RenderTexture rt)
        {
            if (rt == null)
                return;
            Object.Destroy(rt);
        }


        public static Canvas AddWindowCanvas(GameObject go, string layerName, int sortOrder)
        {
            var canvas = go.GetOrAdd<Canvas>();
            canvas.overrideSorting = true;
            canvas.sortingLayerName = layerName;
            canvas.sortingOrder = sortOrder;
            go.GetOrAdd<GraphicRaycaster>();
            return canvas;
        }
    }
}
